const http = require('../request/request')
const cheerio = require ('cheerio')
const SkipCaptcha = require('../common/utils')
const getItemMovieInfo = require('../util/getItemMovieInfo')


const skipCaptchaInstance = new SkipCaptcha()

/**
 * @name postSearchView
 * @description 获取搜索视图
 * @param {string} wd 关键字
 * @param {string} [submit='搜索'] 默认搜索
 * @param {string} [m='vod-search']
 *
*/

// m=vod-search-pg-2-wd-恐怖.html
function postSearchView (wd,submit='搜索',m='vod-search',page=1){
    return new Promise(async (resolve,reject)=>{
        try {
            m = page == 1 ? 'vod-search' : `${m}-pg-${page}-wd-${wd}`
            let {data:_html} = await http({
                method:'POST',
                url:`/index.php?m=${m}`,
                headers:{"Content-type":"application/x-www-form-urlencoded"},
                data:{
                    wd,
                    submit
                }
            })
            resolve(_html)
        } catch (err){
            reject(err)
        }
    })
}


/**
 * @name getSearchResult
 * @description 获取当前搜索结果
 * @returns 返回当前搜索页面的结果信息
*/

function getSearchResult ($){
    try {
        let searchResultObject = {}
        
        // 检查是否有搜索结果
        if ($('.page').length === 0) {
            console.log('未找到分页信息，可能没有搜索结果或页面结构不符合预期');
            searchResultObject['list'] = [];
            searchResultObject['count'] = 0;
            searchResultObject['page_now'] = 1;
            searchResultObject['page_count'] = 1;
            searchResultObject['one_pages_count'] = 0;
            return searchResultObject;
        }
        
        let pageText = $('.page').text();
        if (!pageText.includes('当前:')) {
            console.log('页面结构不符合预期，无法解析分页信息');
            searchResultObject['list'] = [];
            searchResultObject['count'] = 0;
            searchResultObject['page_now'] = 1;
            searchResultObject['page_count'] = 1;
            searchResultObject['one_pages_count'] = 0;
            return searchResultObject;
        }
        
        let pageCountStr = pageText.split('当前:')[1].slice(0, pageText.split('当前:')[1].indexOf('页')).split('/');
        searchResultObject['list'] = [] // 每一项
        searchResultObject['count'] = Number($('.count').text()) || 0 // 数量
        searchResultObject['page_now'] = Number($('.pagenow').text()) || 1 // 当前页面
        searchResultObject['page_count'] = Number(pageCountStr[1]) || 1 // 共几页
        searchResultObject['one_pages_count'] = 18 // 每页最大18条
        
        $('.index-area').find('li').each((index,li)=>{
            try {
                let movieObj = getItemMovieInfo($,li)
                searchResultObject['list'].push(movieObj)
            } catch (err) {
                console.error('解析单个电影项时出错:', err);
            }
        })
        
        return searchResultObject
    } catch (error) {
        console.error('解析搜索结果出错:', error);
        // 返回空结果而不是抛出错误
        return {
            list: [],
            count: 0,
            page_now: 1,
            page_count: 1,
            one_pages_count: 0
        };
    }
}


exports.searchHandler = async (req,res) => {
    res.set('Cache-Control','max-age=100')
    let {page} = req.query // 当前需要第几页数据
    let {wd,submit} = req.body
    console.warn('搜索请求参数:', {wd, submit, page});
    
    if (!wd) {
        return res.send({
            code: 400,
            msg: '搜索关键词不能为空'
        });
    }
    
    try {
        // 先尝试常规搜索
        console.log('尝试常规搜索...');
        let html = await postSearchView(wd,submit,'vod-search',page)
        let $ = cheerio.load(html)
        
        // 如果html里面有系统安全验证 则是需要验证码
        if (html.includes('系统安全验证')) {
            console.log('检测到需要验证码，启动自动验证码处理');
            let searchPath = `https://www.kanyikanys.cc/index.php?m=vod-search-pg-${page}-wd-${encodeURIComponent(wd)}.html`
            
            try {
                // 使用自动验证码识别功能
                console.log('开始自动处理验证码...');
                const content = await skipCaptchaInstance.autoHandleCaptcha(searchPath, wd);
                // console.log('content 自动处理验证码',content)
                if (content) {
                    console.log('验证码处理完成，解析页面内容');
                    // 解析处理后的页面内容
                    $ = cheerio.load(content);
                    
                    // 再次检查是否还需要验证码
                    if (content.includes('系统安全验证')) {
                        console.error('多次尝试后仍需要验证码，可能验证码识别率不高');
                        res.send({
                            code: 101,
                            msg: '验证码处理失败，请稍后再试'
                        });
                        return;
                    }
                    
                    // 成功通过验证码，解析搜索结果
                    console.log('验证码处理成功，开始解析搜索结果');
                    let searchResultObject = getSearchResult($);
                    
                    // 检查结果是否为空
                    if (searchResultObject.list.length === 0) {
                        console.log('搜索结果为空');
                        res.send({
                            code: 200,
                            msg: '未找到相关结果',
                            data: searchResultObject
                        });
                    } else {
                        console.log(`搜索成功，找到 ${searchResultObject.list.length} 条结果`);
                        res.send({
                            code: 200,
                            msg: '获取成功',
                            data: searchResultObject
                        });
                    }
                    return;
                } else {
                    console.error('验证码处理返回空内容');
                    res.send({
                        code: 103,
                        msg: '验证码处理失败，返回空内容'
                    });
                    return;
                }
            } catch (error) {
                console.error('自动处理验证码过程中出错:', error);
                res.send({
                    code: 102,
                    msg: '验证码处理失败: ' + (error.message || '未知错误')
                });
                return;
            }
        }
        
        // 正常情况，没有验证码
        console.log('无需验证码，直接解析搜索结果');
        let searchResultObject = getSearchResult($)
        
        // 检查结果是否为空
        if (searchResultObject.list.length === 0) {
            console.log('搜索结果为空');
            res.send({
                code: 200,
                msg: '未找到相关结果',
                data: searchResultObject
            });
        } else {
            console.log(`搜索成功，找到 ${searchResultObject.list.length} 条结果`);
            res.send({
                code: 200,
                msg: '获取成功',
                data: searchResultObject
            });
        }
    } catch(err){
        console.error('搜索过程中出错:', err);
        res.send({
            code: 100,
            msg: '搜索失败: ' + (err.message || '未知错误')
        });
    }
}
